-- keyboard_input.lua (优化版本)
-- 键盘输入系统：处理所有键盘事件的接收和状态管理

local KeyboardInput = {}
KeyboardInput.__index = KeyboardInput

-- 构造函数：创建新的键盘输入系统
function KeyboardInput.new()
    return setmetatable({
        keyState = {},                     -- 所有按键状态表
        keyDownCallbacks = {},             -- 按键按下回调
        keyUpCallbacks = {},               -- 按键释放回调
        keyPressedCallbacks = {},          -- 按键持续按下回调
        lastKeyState = {}                  -- 上一帧按键状态（用于检测按键变化）
    }, KeyboardInput)
end

-- 处理键盘按下事件
function KeyboardInput:handleKeyDown(keyName)
    self.keyState[keyName] = true
    
    -- 触发按键按下回调
    if self.keyDownCallbacks[keyName] then
        for _, callback in ipairs(self.keyDownCallbacks[keyName]) do
            callback(keyName)
        end
    end
    
    -- 触发通用按键按下回调
    if self.keyDownCallbacks["*"] then
        for _, callback in ipairs(self.keyDownCallbacks["*"]) do
            callback(keyName)
        end
    end
end

-- 处理键盘释放事件
function KeyboardInput:handleKeyUp(keyName)
    self.keyState[keyName] = false
    
    -- 触发按键释放回调
    if self.keyUpCallbacks[keyName] then
        for _, callback in ipairs(self.keyUpCallbacks[keyName]) do
            callback(keyName)
        end
    end
    
    -- 触发通用按键释放回调
    if self.keyUpCallbacks["*"] then
        for _, callback in ipairs(self.keyUpCallbacks["*"]) do
            callback(keyName)
        end
    end
end

-- 获取按键状态
function KeyboardInput:isKeyPressed(keyName)
    return self.keyState[keyName] or false
end

-- 检测按键是否刚刚按下（当前帧按下，上一帧未按下）
function KeyboardInput:isKeyJustPressed(keyName)
    local currentState = self.keyState[keyName] or false
    local lastState = self.lastKeyState[keyName] or false
    return currentState and not lastState
end

-- 检测按键是否刚刚释放（当前帧释放，上一帧按下）
function KeyboardInput:isKeyJustReleased(keyName)
    local currentState = self.keyState[keyName] or false
    local lastState = self.lastKeyState[keyName] or false
    return not currentState and lastState
end

-- 获取所有按键状态
function KeyboardInput:getKeyState()
    return self.keyState
end

-- 获取当前按下的所有按键列表
function KeyboardInput:getPressedKeys()
    local pressedKeys = {}
    for keyName, isPressed in pairs(self.keyState) do
        if isPressed then
            table.insert(pressedKeys, keyName)
        end
    end
    return pressedKeys
end

-- 注册按键按下回调
function KeyboardInput:onKeyDown(keyName, callback)
    if not self.keyDownCallbacks[keyName] then
        self.keyDownCallbacks[keyName] = {}
    end
    table.insert(self.keyDownCallbacks[keyName], callback)
end

-- 注册按键释放回调
function KeyboardInput:onKeyUp(keyName, callback)
    if not self.keyUpCallbacks[keyName] then
        self.keyUpCallbacks[keyName] = {}
    end
    table.insert(self.keyUpCallbacks[keyName], callback)
end

-- 注册通用按键按下回调（所有按键）
function KeyboardInput:onAnyKeyDown(callback)
    if not self.keyDownCallbacks["*"] then
        self.keyDownCallbacks["*"] = {}
    end
    table.insert(self.keyDownCallbacks["*"], callback)
end

-- 注册通用按键释放回调（所有按键）
function KeyboardInput:onAnyKeyUp(callback)
    if not self.keyUpCallbacks["*"] then
        self.keyUpCallbacks["*"] = {}
    end
    table.insert(self.keyUpCallbacks["*"], callback)
end

-- 移除按键回调
function KeyboardInput:removeKeyCallbacks(keyName)
    self.keyDownCallbacks[keyName] = nil
    self.keyUpCallbacks[keyName] = nil
end

-- 清空所有回调
function KeyboardInput:clearAllCallbacks()
    self.keyDownCallbacks = {}
    self.keyUpCallbacks = {}
    self.keyPressedCallbacks = {}
end

-- 更新方法
function KeyboardInput:update(dt)
    -- 更新上一帧按键状态
    self.lastKeyState = {}
    for keyName, isPressed in pairs(self.keyState) do
        self.lastKeyState[keyName] = isPressed
    end
    
    -- 处理持续按下的按键回调
    for keyName, isPressed in pairs(self.keyState) do
        if isPressed and self.keyPressedCallbacks[keyName] then
            for _, callback in ipairs(self.keyPressedCallbacks[keyName]) do
                callback(keyName, dt)
            end
        end
    end
end

-- 注册键盘控制到场景
function KeyboardInput:registerToScene(scene)
    scene.keyboardEnabled = true
    
    -- 注册键盘按下事件处理
    scene:slot("KeyDown", function(keyName)
        self:handleKeyDown(keyName)
    end)
    
    -- 注册键盘释放事件处理
    scene:slot("KeyUp", function(keyName)
        self:handleKeyUp(keyName)
    end)
    
    print("键盘输入系统已注册到场景，支持所有键盘输入")
end

-- 预定义的常用按键名称（根据Dora引擎的KeyName枚举）
-- 添加Shift键支持
KeyboardInput.KeyNames = {
    -- 字母键
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
    
    -- 数字键
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    
    -- 功能键
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
    
    -- 方向键
    "Up", "Down", "Left", "Right",
    
    -- 特殊键
    "Space", "Return", "Enter", "Escape", "Backspace", "Tab", "Shift", "LShift", "RShift", "Control", "LCtrl", "RCtrl", "Alt", "LAlt", "RAlt",
    "CapsLock", "PageUp", "PageDown", "End", "Home", "Insert", "Delete",
    
    -- 符号键
    "Grave", "Minus", "Equal", "LeftBracket", "RightBracket", "BackSlash",
    "Semicolon", "Quote", "Comma", "Period", "Slash",
    
    -- 小键盘
    "Num0", "Num1", "Num2", "Num3", "Num4", "Num5", "Num6", "Num7", "Num8", "Num9",
    "NumLock", "NumDivide", "NumMultiply", "NumMinus", "NumPlus", "NumEnter", "NumDecimal"
}

return KeyboardInput